import axios from 'axios'

export default {
  namespaced: true,
  state(){
    return { 
       list: []
     }
  },
  getters: {
    totalPrice(state) {
      return state.list.reduce((pre, item) => pre + item.price * item.count, 0)
    },
    totalCount(state) {
      return state.list.reduce((pre, item) => pre + item.count, 0)
    }
  },
  mutations: {
    updateList(state, list) {
      state.list = list
    },

    // {id, count}
    updateCount(state, payload){
      const item = state.list.find(item => item.id === payload.id)
      item.count = payload.count
    }
  },
  actions: {
    async getList(ctx){
      const res = await axios.get('http://localhost:3000/cart')
      ctx.commit('updateList', res.data)
    },

    // {id, count}
    async updateCountApi(ctx, payload){
      await axios.patch(`http://localhost:3000/cart/${payload.id}`, {
        count: payload.count
      })
      ctx.commit('updateCount', payload)
    }
  }
}